/*
 *  Take a look at http://www.python.org/extending/embedding.html
 */

#include <stdio.h>
#include <Python.h>
#include "goog_authuser.h"

const char* PYIMPORT = "goog_authuser";
const char* FUNCNAME = "authuser";


//wrapper to the python function found in 

//I'd love to hash password here, but from google can't find a good way to authenticate with it
//so password is plaintext (though still sent to goog over https)

//using this module for authentication my be dangerous. If google changes return values
//it may be possible for unauthorized users to gain access or authed users be denied access
//although I have no control over this, I will fix any issues as soon as possible - and it
//would be a very easy fix.

int authuser(char* username, char* domain, char* password) {
  PyObject *pName, *pModule, *pFunc;
  PyObject *pArgs, *p_userValue, *p_domainValue, *p_passValue;
  PyObject *retval;
  int i;

  //TODO error check arguments
  Py_Initialize();

  //PYIMPORT defined in goog_authuser.h
  pName = PyString_FromString(PYIMPORT);
  pModule = PyImport_Import(pName);
  Py_DECREF(pName);

  if (pModule != NULL) {
    //FUNCNAME from goog_authuser.h
    pFunc = PyObject_GetAttrString(pModule, FUNCNAME);
    if (pFunc && PyCallable_Check(pFunc)) {
      //assign number of args to 3
      pArgs = PyTuple_New(3);
      p_userValue = PyString_FromString(username);
      p_domainValue = PyString_FromString(domain);
      p_passValue = PyString_FromString(password);
      if (!p_userValue || !p_passValue || !p_domainValue) {
        Py_DECREF(pArgs);
        Py_DECREF(pModule);
        printf("Cannot convert argument - error\n");
        return -1;
      }

      PyTuple_SetItem(pArgs, 0, p_userValue);
      PyTuple_SetItem(pArgs, 1, p_domainValue);
      PyTuple_SetItem(pArgs, 2, p_passValue);

      retval = PyObject_CallObject(pFunc, pArgs); 

      Py_DECREF(p_userValue);
      Py_DECREF(p_passValue);
      Py_DECREF(p_domainValue);
      Py_DECREF(pArgs);

      if (retval != NULL) {
        printf("Result of call: %ld\n", PyInt_AsLong(retval));
        Py_DECREF(retval);
      }
      else {
        Py_DECREF(pFunc);
        Py_DECREF(pModule);
        PyErr_Print();
        return -1;
      }
    }
    else {
      if (PyErr_Occurred())
        PyErr_Print();
      printf("Cannot find function\n");
      Py_XDECREF(pFunc);
      Py_DECREF(pModule);
    }
  }
  else {
    PyErr_Print();
    printf("Failed to load module\n");
    return -1;
  }
  Py_Finalize();
  return 0;
}


